<?php namespace Phpcmf\Controllers\Member;

class Son extends \Phpcmf\Table
{

    public $cid; // 内容id
    public $form; // 表单信息

    public function __construct(...$params) {
        parent::__construct(...$params);
        // 初始化模块
        $this->_module_init(APP_DIR);
        // 判断表单是否操作
        $this->form = $this->module['form'][\Phpcmf\Service::L('Router')->class];
        !$this->form && $this->_msg(0, dr_lang('模块表单【%s】不存在', \Phpcmf\Service::L('Router')->class));
        // 支持附表存储
        $this->is_data = 1;
        // 模板前缀(避免混淆)
        $this->tpl_prefix = '';
        // 单独模板命名
        $this->tpl_name = 'son';
        // 模块显示名称
        $this->name = dr_lang('内容模块[%s]表单（%s）', APP_DIR, $this->form['name']);
        // 获取父级内容
        $this->cid = intval(\Phpcmf\Service::L('Input')->get('cid'));
        if ($this->cid) {
            $this->index = $this->content_model->get_row( $this->cid);
            $this->index['uid'] != $this->uid && $this->_msg(0, dr_lang('无权限操作他人数据'));
        }
        // 自定义条件
        $where = 'cid='. $this->cid;
        $sysfield = ['displayorder'];
        // 初始化数据表
        $this->_init([
            'field' => $this->form['field'],
            'table' => dr_module_table_prefix(APP_DIR).'_form_'.$this->form['table'],
            'sys_field' => $sysfield,
            'date_field' => 'inputtime',
            'list_field' => $this->form['setting']['list_field'],
            'show_field' => 'title',
            'order_by' => 'inputtime desc',
            'where_list' => $where,
        ]);
        // 写入模板
        \Phpcmf\Service::V()->assign([
            'mform' => $this->form,
            'index' => $this->index,
        ]);
    }

    public function index() {
        $this->init['order_by'] = 'displayorder asc,id asc';
        list($tpl, $data) = $this->_List(['cid' =>  $this->cid], -1);
        \Phpcmf\Service::V()->assign([
            'p' => ['cid' =>  $this->cid],
            'list' => dr_format_son_list($data['list'], $this->index['son_type']),
            'stype' => dr_son_type($this->index['son_type']),
        ]);
        \Phpcmf\Service::V()->display('son_list.html');
    }

    public function add() {

        !$this->cid && $this->_msg(0, dr_lang('缺少cid参数'));


        // 是否有验证码
        $this->is_post_code = dr_member_auth(
            $this->member_authid,
            $this->member_cache['auth_module'][SITE_ID][MOD_DIR]['form'][$this->form['table']]['code']
        );
        list($tpl) = $this->_Post(0);

        \Phpcmf\Service::V()->assign([
            'form' =>  dr_form_hidden(),
            'is_post_code' => $this->is_post_code,
        ]);
        \Phpcmf\Service::V()->display($tpl);

    }

    public function edit() {

        !$this->cid && $this->_msg(0, dr_lang('缺少cid参数'));

        $id = intval(\Phpcmf\Service::L('Input')->get('id'));

        // 是否有验证码
        $this->is_post_code = dr_member_auth(
            $this->member_authid,
            $this->member_cache['auth_module'][SITE_ID][MOD_DIR]['form'][$this->form['table']]['code']
        );
        
        list($tpl, $data) = $this->_Post($id);

        !$data && $this->_msg(0, dr_lang('数据不存在: '.$id));
        $this->cid != $data['cid'] && $this->_msg(0, dr_lang('cid不匹配'));

        \Phpcmf\Service::V()->assign([
            'form' =>  dr_form_hidden(),
            'is_post_code' => $this->is_post_code,
        ]);
        \Phpcmf\Service::V()->display($tpl);
    }

    public function order_edit() {
        $this->_Display_Order(
            intval(\Phpcmf\Service::L('Input')->get('id')),
            intval(\Phpcmf\Service::L('Input')->get('value'))
        );
    }

    public function del() {
        $this->_Del(
            \Phpcmf\Service::L('Input')->get_post_ids(),
            null,
            function ($rows) {
                // 对应删除提醒
                foreach ($rows as $t) {
                    \Phpcmf\Service::M('member')->delete_admin_notice(MOD_DIR.'/'.$this->form['table'].'_verify/edit:cid/'.$t['cid'].'/id/'.$t['id'], SITE_ID);// clear
                    \Phpcmf\Service::L('cache')->clear('module_'.MOD_DIR.'_from_'.$this->form['table'].'_show_id_'.$t['id']);
                }
            },
            \Phpcmf\Service::M()->dbprefix($this->init['table'])
        );
    }


    // 隐藏或者启用
    public function vip_edit() {

        $id = (int)\Phpcmf\Service::L('Input')->get('id');
        $row =\Phpcmf\Service::M()->table($this->init['table'])->get($id);
        !$row && $this->_json(0, dr_lang('数据不存在'));

        $v = $row['vip'] ? 0 : 1;
        \Phpcmf\Service::M()->table($this->init['table'])->update($id, ['vip' => $v]);

        exit($this->_json(1, dr_lang($v ? '已设置收费' : '已设置免费'), ['value' => $v]));
    }

    // 分类操作
    public function son_add() {

        if (IS_POST) {
            $name = dr_safe_replace($_POST['name']);
            !$name && $this->_json(0, dr_lang('名称没有填写'));
            $stype = dr_son_type($this->index['son_type']);
            $stype[] = $name;
            \Phpcmf\Service::M()->table(dr_module_table_prefix(APP_DIR))->update($this->cid, [
                'son_type' => dr_array2string($stype)
            ]);
            $this->_json(1, dr_lang('操作成功'));
        }

        \Phpcmf\Service::V()->assign([
            'value' => '',
        ]);
        \Phpcmf\Service::V()->display('son_name.html');exit;
    }

    public function son_edit() {

        $tid = intval($_GET['tid']);
        $stype = dr_son_type($this->index['son_type']);

        if (IS_POST) {
            $name = dr_safe_replace($_POST['name']);
            !$name && $this->_json(0, dr_lang('名称没有填写'));
            $stype[$tid] = $name;
            \Phpcmf\Service::M()->table(dr_module_table_prefix(APP_DIR))->update($this->cid, [
                'son_type' => dr_array2string($stype)
            ]);
            $this->_json(1, dr_lang('操作成功'));
        }

        \Phpcmf\Service::V()->assign([
            'value' => $stype[$tid],
        ]);
        \Phpcmf\Service::V()->display('son_name.html');exit;

    }

    /**
     * 获取内容
     * $id      内容id,新增为0
     * */
    protected function _Data($id = 0) {

        $row = $this->content_model->get_form_row($id, $this->form['table']);
        if (!$row) {
            return [];
        }

        return $row;
    }

    // 格式化保存数据 保存之前
    protected function _Format_Data($id, $data, $old) {

        // 验证父数据
        !$this->index && $this->_json(0, dr_lang('关联内容不存在'));

        // 默认数据
        $data[0]['uid'] = $data[1]['uid'] = (int)$this->member['uid'];
        $data[1]['author'] = $this->member['username'] ? $this->member['username'] : 'guest';
        $data[1]['cid'] = $data[0]['cid'] =  $this->cid;
        $data[1]['catid'] = $data[0]['catid'] = (int)$this->index['catid'];
        $data[1]['inputip'] = \Phpcmf\Service::L('Input')->ip_address();
        $data[1]['inputtime'] = SYS_TIME;

        // 审核状态
        $is_verify = dr_member_auth(
            $this->member_authid,
            $this->member_cache['auth_module'][SITE_ID][MOD_DIR]['form'][$this->form['table']]['verify']
        );
        $data[1]['status'] = $is_verify ? 0 : 1;

        if (!$id) {
            $data[1]['tableid'] = 0;
            $data[1]['displayorder'] = 0;
        }

        return $data;
    }

    /**
     * 保存内容
     * $id      内容id,新增为0
     * $data    提交内容数组,留空为自动获取
     * $func    格式化提交的数据
     * */
    protected function _Save($id = 0, $data = [], $old = [], $func = null, $func2 = null) {

        return parent::_Save($id, $data, $old, null,
            function ($id, $data, $old) {
                //审核通知
                if ($data[1]['status']) {
                    // 增减金币
                    $score = $this->_member_value($this->member_authid, $this->member_cache['auth_module'][SITE_ID][MOD_DIR]['form'][$this->form['table']]['score']);
                    $score && \Phpcmf\Service::M('member')->add_score($this->member['uid'], $score, dr_lang('%s: %s发布', MODULE_NAME, $this->form['name']), $this->index['curl']);
                    // 增减经验
                    $exp = $this->_member_value($this->member_authid, $this->member_cache['auth_module'][SITE_ID][MOD_DIR]['form'][$this->form['table']]['exp']);
                    $exp && \Phpcmf\Service::M('member')->add_experience($this->member['uid'], $exp, dr_lang('%s: %s发布', MODULE_NAME, $this->form['name']), $this->index['curl']);
                    // clear
                    \Phpcmf\Service::L('cache')->clear('module_'.MOD_DIR.'_from_'.$this->form['table'].'_show_id_'.$id);
                    // 保存之后的更新total字段
                    $this->content_model->update_form_total( $this->cid, $this->form['table']);
                } else {
                    \Phpcmf\Service::M('member')->admin_notice(SITE_ID, 'content', $this->member, dr_lang('%s: %s提交内容审核', MODULE_NAME, $this->form['name']), MOD_DIR.'/'.$this->form['table'].'_verify/edit:cid/'. $this->cid.'/id/'.$id, SITE_ID);
                }
            }
        );
    }
}
